//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin } from '@/api/user';
//引入数据类型
import type { loginForm,loginResponseData } from '@/api/user/type';
import type {UserState} from '@/store/modules/types/type' ;
import { SET_TOKEN,GET_TOKEN } from '@/utils/token';
//创建用户小仓库
export const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: ():UserState => ({
    // token: localStorage.getItem('TOKEN'),//用户唯一标志token
    token:GET_TOKEN(),
    
  }),
  //异步或者逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginForm) {
      // console.log(data)
      //登录请求
      let result:loginResponseData = await reqLogin(data);
      // 登录请求:成功200->token
      // 登录请求:失败 201->登录失败错误的信息
      if(result.code === 200){
        //pinia仓库存储一下token
        this.token=(result.data.token as string);
        console.log('登录成功'+this.token);
        // localStorage.setItem('TOKEN',(result.data.token as string));
        SET_TOKEN((result.data.token as string));
        //能保证当前async函数返回一个成功的promise对象
        return 'ok';
      }else{
        console.log(result.data.token);
        return Promise.reject(new Error(result.data.message));
      }
      console.log(result);
      // we could do other stuff like redirecting the user
    },

    /**
     * Attempt to login a user
     */

  },

})
//对外暴露获取小仓库的方法
export default useUserStore;